package hhf.services {
	import flash.events.EventDispatcher;

	import hhf.services.events.ServiceEvent;

	import mx.core.FlexGlobals;
	import mx.rpc.AbstractOperation;
	import mx.rpc.IResponder;
	import mx.resources.ResourceManager;
	import mx.rpc.Responder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	import mx.utils.ObjectUtil;

	[ResourceBundle("ascreator")]

	[ExcludeClass]
	public class AbstractROService extends EventDispatcher {

		public var serviceControl:RemoteObject;

		[Inspectable(defaultValue=true, verbose=1, type="Boolean")]
		public function set showBusyCursor(showBusyCursor:Boolean):void {
			this.serviceControl.showBusyCursor = showBusyCursor;
		}
		public function get showBusyCursor():Boolean {
			return this.serviceControl.showBusyCursor;
		}

		public function AbstractROService(destination:String) {
			this.serviceControl = new RemoteObject();
			this.serviceControl.endpoint = ResourceManager.getInstance().getString("ascreator", "AMF");
			this.serviceControl.destination = destination;
			this.serviceControl.showBusyCursor = false;
		}

		protected function getResponder(operationName:String, uid:String):IResponder {
			var obj:AbstractROService = this;
			return new Responder(
				function(event:ResultEvent):void {
					FlexGlobals.topLevelApplication.dispatchEvent(new ServiceEvent(ServiceEvent.SUCCESS, uid, ObjectUtil.getClassInfo(obj).name+"."+operationName));
				},
				function(event:FaultEvent):void {
					event.stopImmediatePropagation();
					var evt:FaultEvent = new FaultEvent(FaultEvent.FAULT, true, true, event.fault, event.token, event.message);
					obj.dispatchEvent(evt);
					FlexGlobals.topLevelApplication.dispatchEvent(new ServiceEvent(ServiceEvent.FAIL, uid, ObjectUtil.getClassInfo(obj).name+"."+operationName, event.message));
				}
			)
		}

		protected function getOperation(operationName:String, uid:String):AbstractOperation {
//			setLocaleToRequest();
			var obj:AbstractROService = this;
			FlexGlobals.topLevelApplication.dispatchEvent(new ServiceEvent(ServiceEvent.START, uid, ObjectUtil.getClassInfo(obj).name+"."+operationName));
			var operation:AbstractOperation = serviceControl.getOperation(operationName);
			return operation;
		}

		private function setLocaleToRequest():void {
			var pattern:RegExp =/language=.*/;
			var language:String = "en";
			var currentLocale:String = ResourceManager.getInstance().localeChain[0];
			if(currentLocale) language = currentLocale.split("_")[0];
			this.serviceControl.endpoint = this.serviceControl.endpoint.replace(pattern, "language="+language);
		}
	}
}